<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%">
    <el-form :model="dataForm" label-width="100px" :rules="dataRule" ref="dataForm">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="分类名称" prop="cateId">
            <el-input
              placeholder="请选择分类"
              v-model="dataForm.cateName"
              type="text"
              readonly>
              <template slot="suffix">
                <el-button class="el-icon-edit" @click="checkSort" type="text">选择分类</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="设备编号" prop="deviceSerialNumber">
            <el-input v-model="dataForm.deviceSerialNumber" placeholder="请输入设备编号"></el-input>
          </el-form-item>
          <el-form-item label="区域" prop="areaId">
            <el-select
              filterable
              v-model="dataForm.areaId"
              placeholder="请选择区域"
              clearable
              style="width:100%"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="煤安标志" prop="mark">
            <el-input v-model="dataForm.mark" placeholder="请输入标志"></el-input>
          </el-form-item>
          <el-form-item label="净值" prop="netWorth">
            <el-input type="number" v-model="dataForm.netWorth" placeholder="请输入净值"></el-input>
          </el-form-item>
          <el-form-item label="出厂编号" prop="factoryNumber">
            <el-input v-model="dataForm.factoryNumber" placeholder="请输入出厂编号"></el-input>
          </el-form-item>
          <el-form-item label="使用/存放地点" prop="useStorageLocation">
            <el-input v-model="dataForm.useStorageLocation" placeholder="请输入存放地点"></el-input>
          </el-form-item>
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="dataForm.manufacturer" placeholder="请输入生产厂家"></el-input>
          </el-form-item>
          <el-form-item label="出厂时间" prop="deliveryTime">
            <el-date-picker
              v-model="dataForm.deliveryTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="数量" prop="number">
            <el-input-number :min="1" v-model="dataForm.number" placeholder="请输入数量"></el-input-number>
          </el-form-item>
          <el-form-item label="设备状态" prop="status">
            <!--            <el-input v-model="dataForm.status" placeholder="请输入设备状态"></el-input>-->
            <el-select v-model="dataForm.status" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in deveiceStatusList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="防爆合格证" prop="certificate">
            <el-input v-model="dataForm.certificate" placeholder="请输入合格证"></el-input>
          </el-form-item>
          <el-form-item label="原值" prop="originalValue">
            <el-input type="number" v-model="dataForm.originalValue" placeholder="请输入原值"></el-input>
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="dataForm.specification" placeholder="请输入规格型号"></el-input>
          </el-form-item>
          <el-form-item label="技术参数" prop="technicalParameter">
            <el-input v-model="dataForm.technicalParameter" placeholder="请输入技术参数"></el-input>
          </el-form-item>
          <el-form-item label="使用单位" prop="useCompany">
            <el-input v-model="dataForm.useCompany" placeholder="请输入单位名称"></el-input>
          </el-form-item>
          <el-form-item label="购买时间" prop="purchaseTime">
            <el-date-picker
              v-model="dataForm.purchaseTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="使用时间" prop="usageTime">
            <el-date-picker
              v-model="dataForm.usageTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col  label="每日上报时间">
          <el-form-item label="每日上报时间" prop="dailyReportTime">
            <el-button type="text" @click="addTime()">添加时间</el-button>
            <div v-for="(item, index) in dataForm.dailyReportTime" :key="index">
              <el-time-picker
                arrow-control
                v-model="item[0]"
                value-format="HH:mm"
                @change="changeTime"
                placeholder="开始时间">
              </el-time-picker>
              ~
              <el-time-picker
                arrow-control
                v-model="item[1]"
                value-format="HH:mm"
                @change="changeTimes"
                placeholder="结束时间">
              </el-time-picker>
<!--              v-if="dataForm.dailyReportTime.length > 1"-->
              <i class="el-icon-delete" @click="timeDelete(index)"></i>
            </div>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="包机负责人" prop="userList">
            <template slot-scope="">
              <div
                class="learn-drawer-range-box"
                style="margin-top: 10px"
              >
                <p>
                  <el-tag
                    style="margin: 5px"
                    v-for="x in userList"
                    :key="x.userId"
                    @close="handleClose(x.userId)"
                    closable
                  >{{x.realname}}
                  </el-tag>
                </p>
                <div class="learn-drawer-range-box-buttons">
                  <el-button type="danger" round @click="handleCloses()">清空</el-button>
                  <el-button type="primary" round @click="openCheckPeople">添加</el-button>
                </div>
              </div>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="onsubmit" :loading="loading">确定</el-button>
    </span>
    <el-dialog
      title="分类管理"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
      append-to-body
      width="40%"
    >
      <paper-cate
        ref="paperCate"
        type="配置分类"
        :setCurrent="setCurrent"
        :current="current"
        :url="{
                update:'/device/devicecate/update',
                save:'/device/devicecate/save',
                delete:'/device/devicecate/delete',
                tree:'/device/devicecate/tree'
        }"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <checkPeople :checked-user-list="userList" :set-user-list="setUserList" ref="checkPeople"/>
  </el-dialog>
</template>

<script>
  import paperCate from '../paper/papercate'
  import checkPeople from '../../../components/check/checkPeople'
  export default {
    name: 'device-add-or-update',
    data () {
      return {
        loading: false,
        dialogFormVisible: false,
        current: {},
        userList: [],
        deveiceStatusList: [
          {
            key: 1,
            value: '在用'
          },
          {
            key: 2,
            value: '闲置'
          },
          {
            key: 3,
            value: '待修'
          },
          {
            key: 4,
            value: '借入'
          },
          {
            key: 5,
            value: '借出'
          },
          {
            key: 6,
            value: '报废'
          },
          {
            key: 7,
            value: '其他'
          }
        ],
        dataForm: {
          id: '',
          name: '',
          certificate: '',
          cateId: '',
          deliveryTime: '',
          cateName: '',
          useStorageLocation: '',
          deviceSerialNumber: '',
          factoryNumber: '',
          manufacturer: '',
          mark: '',
          dailyReportStartTime: '',
          dailyReportTime: [],
          netWorth: '',
          areaId: '',
          areaName: '',
          number: 1,
          originalValue: '',
          userList: [],
          time: [],
          purchaseTime: '',
          specification: '',
          status: '',
          technicalParameter: '',
          usageTime: '',
          useCompany: '',
          userIds: '',
          statusTime: ''
        },
        areaList: [],
        dataRule: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          cateId: [
            { required: true, message: '分类名称不能为空', trigger: 'blur' }
          ],
          // status: [
          //   { required: true, message: '设备状态不能为空', trigger: 'blur' }
          // ],
          // useCompany: [{ required: true, message: '使用单位不能为空', trigger: 'change' }],
          deviceSerialNumber: [
            { required: true, message: '设备编号不能为空', trigger: 'blur' }
          ],
          // userList: [{type: 'array', required: true, message: '请至少选择一个负责人', trigger: 'change'}]
        },
        visible: false,
        paperCate: false
      }
    },
    props: ['getDataList'],
    components: { paperCate, checkPeople },
    methods: {
      async open (id) {
        this.dataForm.dailyReportTime = []
        this.dataForm.cateName = ''
        this.dataForm.dailyReportStartTime = ''
        this.dataForm.dailyReportEndTime = ''
        this.dataForm.id = id
        this.userList = []
        this.getAreaList()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
        this.visible = true
        if (id) {
          let res = await this.$http.post(`/device/devicemanagement/info/${id}`)
          this.buildDataForm(res.data)
        }
      },
      changeTime(val) {
        if (this.dataForm.dailyReportEndTime !== '' && val > this.dataForm.dailyReportEndTime) {
          console.log(this.dataForm.dailyReportEndTime)
          this.$notify.error({ title: '失败', message: '结束时间不能小于开始时间，请重新输入' })
          this.dataForm.statusTime = 1
          return false
        } else {
          this.dataForm.statusTime = 0
        }
        if (val < this.dataForm.dailyReportEndTime) {
          this.$notify.error({ title: '失败', message: '不能小于上一个结束时间，请重新输入' })
          return false
        } else {
          this.dataForm.dailyReportStartTime = val
          if (this.dataForm.time[0] !== '') {
            this.dataForm.time.splice(1)
          }
          this.dataForm.time.push(val)
        }
      },
      changeTimes(val) {
        if (val < this.dataForm.dailyReportStartTime) {
          this.$notify.error({ title: '失败', message: '结束时间不能小于开始时间，请重新输入' })
          this.dataForm.statusTime = 1
          return false
        } else {
          this.dataForm.statusTime = 0
          this.dataForm.dailyReportEndTime = val
          if (this.dataForm.time[1] !== '') {
            this.dataForm.time.splice(1)
          }
          this.dataForm.time.push(val)
        }
      },
      addTime() {
        if (this.dataForm.dailyReportTime === null) {
          this.dataForm.dailyReportTime = []
        }
        this.dataForm.time = []
        this.dataForm.dailyReportTime.push(this.dataForm.time)
      },
      timeDelete(i) {
        this.dataForm.dailyReportTime.splice(i, 1)
      },
      async getAreaList() {
        var res = await this.$http.post('device/area/list')
        this.areaList = res.data
      },
      setUserList(data) {
        data.forEach(user => {
          if (this.userList.findIndex(x => x.userId === user.userId) === -1) {
            this.userList.push(user)
          }
        })
      },
      handleClose(userId) {
        var index = this.userList.findIndex(x => x.userId === userId)
        this.userList.splice(index, 1)
      },
      handleCloses() {
        this.userList = []
      },
      // 添加人员
      openCheckPeople() {
        this.$nextTick(() => {
          this.$refs['checkPeople'].init(this.dataForm.userList)
        })
      },
      setCurrent(data) {
        this.dataForm.cateId = data.id
        this.dataForm.cateName = data.name
        if (data.id) this.current = data
      },
      checkSort() {
        this.paperCate = true
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.paperCate.init()
        })
      },
      buildDataForm(data) {
        this.dataForm.id = data.id
        this.dataForm.cateId = data.cateId
        this.dataForm.name = data.name
        this.dataForm.cateName = data.cateName
        this.dataForm.deviceSerialNumber = data.deviceSerialNumber
        this.dataForm.specification = data.specification
        this.dataForm.useStorageLocation = data.useStorageLocation
        this.dataForm.manufacturer = data.manufacturer
        this.dataForm.technicalParameter = data.technicalParameter
        this.dataForm.mark = data.mark
        this.dataForm.originalValue = data.originalValue
        this.dataForm.dailyReportTime = data.dailyReportTime ? JSON.parse(data.dailyReportTime) : []
        this.dataForm.dailyReportEndTime = data.dailyReportEndTime
        this.dataForm.certificate = data.certificate
        this.dataForm.certificate = data.certificate
        this.dataForm.number = data.number
        this.dataForm.areaId = data.areaId
        this.dataForm.areaName = data.areaName
        this.dataForm.deliveryTime = data.deliveryTime
        this.dataForm.factoryNumber = data.factoryNumber
        this.dataForm.purchaseTime = data.purchaseTime
        this.dataForm.usageTime = data.usageTime
        this.dataForm.status = data.status
        this.userList = data.userList !== null ? data.userList : []
        this.dataForm.netWorth = data.netWorth
        this.dataForm.useCompany = data.useCompany
      },
      buildRequest() {
        return {
          id: this.dataForm.id || undefined,
          cateId: this.dataForm.cateId || undefined,
          name: this.dataForm.name,
          certificate: this.dataForm.certificate,
          deliveryTime: this.dataForm.deliveryTime,
          deviceSerialNumber: this.dataForm.deviceSerialNumber,
          factoryNumber: this.dataForm.factoryNumber,
          manufacturer: this.dataForm.manufacturer,
          useStorageLocation: this.dataForm.useStorageLocation,
          mark: this.dataForm.mark,
          status: this.dataForm.status,
          areaId: this.dataForm.areaId,
          netWorth: this.dataForm.netWorth,
          dailyReportStartTime: this.dataForm.dailyReportStartTime,
          dailyReportEndTime: this.dataForm.dailyReportEndTime,
          number: this.dataForm.number,
          dailyReportTime: this.dataForm.dailyReportTime.length > 0 ? JSON.stringify(this.dataForm.dailyReportTime) : '',
          originalValue: this.dataForm.originalValue,
          purchaseTime: this.dataForm.purchaseTime,
          technicalParameter: this.dataForm.technicalParameter,
          usageTime: this.dataForm.usageTime,
          useCompany: this.dataForm.useCompany,
          userIds: this.dataForm.userList !== null ? this.dataForm.userList.map(x => x).join(',') : [],
          specification: this.dataForm.specification
        }
      },
      async onsubmit() {
        if (this.dataForm.statusTime === 1) {
          this.$notify.error({ title: '失败', message: '上报时间错误，请重新输入' })
          return false
        }
        var keyIndex = JSON.stringify(this.dataForm.dailyReportTime).indexOf(null)
        if (keyIndex > -1) {
          this.$notify.error({ title: '失败', message: '上报时间错误' })
          return false
        }
        var isValid = await this.$refs.dataForm.validate()
        if (!isValid) return

        let res = await this.$http({
          url: this.$http.adornUrl(`/device/devicemanagement/${!this.dataForm.id ? 'save' : 'update'}`),
          method: 'post',
          data: this.buildRequest()
        })
        if (res.code === 200) {
          this.visible = false
          this.$emit('refreshDataList')
        }
      }
    },
    watch: {
      'userList'(val) {
        if(val !== null) {
          this.dataForm.userList = val.map(x => x.userId)
        }
      }
    }
  }
</script>

<style scoped>

</style>
